/*
 * @Description: 
 * @Author: chenjiaxin
 * @Date: 2021-12-20 21:42:30
 * @LastEditTime: 2022-01-08 19:18:00
 * @FilePath: \novel-serve\src\controller\auth.controller.js
 */
const jwt = require('jsonwebtoken');
const { PRIVATE_KEY, } = require('../app/config');
const errorTypes = require('../constants/error-types');
const service = require("../service/user.service");
const { responseHandle } = require('../utils/tool');

class AuthController {
  async login(ctx, next) {
    try {
      
      console.log(ctx.user, '用户信息');
      let { id, e_mail } = ctx.user;
      //颁发token
      const token = jwt.sign({ id, e_mail }, PRIVATE_KEY, {
        expiresIn: 24 * 60 * 60, // 一天
        algorithm: 'RS256'
      })

      //获取用户信息
      const user = await service.getUserByEmail(e_mail);
      delete user.password;
      console.log("获取用户信息", user);
      // ctx.body = {
      //   code: 200,
      //   data: {
      //     user,
      //     token,
      //   }
      // };
      ctx.body = responseHandle(200, {user, token});
      

    } catch (error) {
      console.log(error); 
      return ctx.app.emit('error', errorTypes.SYNTAX_ERROR, ctx, error.message);
    }
  }
}

module.exports = new AuthController();
